package com.example.demo.Service;

import com.example.demo.entity.Message;
import com.example.demo.repository.MessageRepository;
import com.example.demo.specifications.MessageSpecifications;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageService {

    @Autowired
    private MessageRepository messageRepository;
    private MessageSpecifications messageSpecifications;

    public Message createMessage(Long senderId, Long receiverId, String content) {
        Message message = new Message();
        message.setSenderId(senderId);
        message.setReceiverId(receiverId);
        message.setContent(content);
        message.setIsRead(false); // 默认为未读
        return messageRepository.save(message);
    }

    public void deleteMessage(Long messageId) {
        messageRepository.deleteById(messageId);
    }

    public Message updateMessageStatus(Long messageId, Boolean isRead) {
        Message message = messageRepository.findById(messageId).orElse(null);
        if (message != null) {
            message.setIsRead(isRead);
            return messageRepository.save(message);
        }
        return null;
    }
    public Message getLatestMessageByreceiverId(Long receiverId) {
        return messageRepository.findLatestByReceiverId(receiverId);
    }
    public Iterable<Message> listAllMessages() {
        return messageRepository.findAll();
    }

    public List<Message> listMessagesByReceiverId(Long receiverId) {
        return messageRepository.findAll().stream()
                .filter(m -> m.getReceiverId().equals(receiverId))
                .collect(Collectors.toList());
    }

    public List<Message> getConversationBetweenUsers(Long senderId, Long receiverId) {
        Specification<Message> spec = MessageSpecifications.conversationBetweenUsers(senderId, receiverId);
        return messageRepository.findAll(spec);
    }

    // 更多业务方法...
}